/**
 * canvas Class
 */

// 公有渲染方法
function commonRender(ctx, obj){
    /** @type {HTMLCanvasElement} */
    let {x, y, fillStyle, strokeStyle, rotaion, scaleX, scaleY} = obj
    ctx.save()
    ctx.beginPath()

    // 移动
    ctx.translate(x,y)
    // 旋转
    ctx.rotate(rotaion)
    // 缩放
    ctx.scale(scaleX, scaleY)
    // 填充颜色
    ctx.fillStyle = fillStyle
    // 描边颜色
    ctx.strokeStyle = strokeStyle
}

//  公有初始化方法
function commonInit(obj){
    obj.x = 0
    obj.y = 0
    obj.rotaion = 0
    obj.scaleX = 1
    obj.scaleY = 1
    obj.ax = 0
    obj.ay = 0
    obj.vx = 0
    obj.vy = 0
    obj.fillStyle = 'rgba(0,0,0,1)'
    obj.strokeStyle = 'rgba(0,0,0,1)'
    obj.rotaionRate = 0
    obj.scaleXRate = 0
    obj.scaleYRate = 0
    obj.updateFunc = Object
    return obj
}

// 公有更新函数
function commonUpdate(ctx, obj){
    obj.vx +=  obj.ax
    obj.vy +=  obj.ay
    obj.x +=  obj.vx
    obj.y +=  obj.vy
    obj.rotaion +=  obj.rotaion
    obj.scaleX +=  obj.scaleXRate
    obj.scaleY +=  obj.scaleYRate
    obj.render(ctx)
    return obj
}


class Boll{
    /**
     * 小球类
     */
   constructor(props){
        commonInit(this)
        this.r = 20
        this.startAngle = 0
        this.endAngle = Math.PI * 2
        this.counterclockwise = true
        Object.assign(this, props)
        return this
    }

    update(ctx){
        this.updateFunc(this)
        commonUpdate(ctx, this)
        return this
    }

    render(ctx){
        commonRender(ctx, this)
        // 复原画布
        ctx.arc(0, 0, this.r, this.startAngle, this.endAngle, this.counterclockwise)
        ctx.fill()
        ctx.restore()
        return this
    }
}

// 文字类
class TextStyle{
    constructor(props){
        commonInit(this)
        this.text = ''
        this.font = '100px cursive'
        this.shadowColor = false
        Object.assign(this, props)
        return this
    }

    update(ctx){
        this.updateFunc(this)
        commonUpdate(ctx, this)
        return this
    }

    render(ctx){
        commonRender(ctx, this)
        ctx.font = this.font;
        for (var i = 0; i < 5; i++) {
            ctx.fillText(this.text , 0, 0)
            ctx.strokeStyle = this.strokeStyle
            ctx.stroke()
            if(this.shadowColor){
                ctx.shadowColor = this.shadowColor.slice(0,this.shadowColor.lastIndexOf(',') + 1) + (5 - i) / 5 + ')'
                ctx.shadowOffsetX = i + 4
                ctx.shadowOffsetY = i * 4
                ctx.shadowBlur = i * 4
            }
        }
        ctx.restore()
        return this
    }
}

export  {
    Boll,
    TextStyle
}